# -*- coding: utf-8 -*-
import datetime
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import HttpResponse
from django.utils import simplejson
from okuz.visit.models import *
from okuz.visit.forms import DateForm, VisitForm


ORDERS = {'asc':'date', 'desc':'-date'};
DEFAULT = {'sort':'desc', 'item':'50', 'page':'1'};

def archive (request):
	param = {'sort':request.GET.get ('sort', DEFAULT['sort']),
			'item':request.GET.get ('item', DEFAULT['item']),
			'page':request.GET.get ('page', DEFAULT['page']),
			'month':request.GET.get ('month', 0),
			'year':request.GET.get ('year', 0), };
	if request.POST or param['year'] > 0:
		param['year'] = request.POST.get ('year', param['year']);
		param['month'] = request.POST.get ('month', param['month']);
		archive = Visit.objects.filter (date__year = param['year'], date__month = param['month']).order_by (ORDERS[param['sort']]);
		form = DateForm (request.POST);
	else:
		archive = Visit.objects.all ().order_by (ORDERS[param['sort']]);
		form = DateForm ()
	paginator = Paginator (archive, param['item']);
	try:
		archivePage = paginator.page (param['page']);
	except PageNotAnInteger:
		archivePage = paginator.page (1);
	except EmptyPage:
		archivePage = paginator.page (paginator.num_pages);
	return render_to_response ('visit/archive.html',
								{'archives':archivePage, 'param':param, 'form':form},
    							context_instance = RequestContext (request));

def show (request, id):
	try:
		visit = Visit.objects.get (id = id);
	except:
		return error (request, u"Wystąpił błąd ;-(", u"Nie mogę pobrać wizyty dla id = "+id);
	return render_to_response ('visit/show.html', {'visit':visit},
								context_instance = RequestContext (request));

def user (request, id):
	try:
		profile = Profile.objects.get (id = id);
		visit = Visit.objects.filter (profile = profile);
	except:
		return error (request, u"Wystąpił błąd ;-(", u"Nie mogę pobrać wizyt dla id = "+id);
	return render_to_response ('visit/user.html', {'visit':visit, 'profile':profile},
								context_instance = RequestContext (request));

def add (request, id):
	data = dict ();
	data['date'] = datetime.datetime.now ();
	if int (id) > 0:
		data['name'] = Profile.objects.get (id = id);
	if request.POST:
		form = VisitForm (request.POST);
		if form.is_valid ():
			leave_from = request.POST.get ('leave_from', 0);
			leave_to = request.POST.get ('leave_to', 0);
			comment = request.POST.get ('comment', '');
			if comment:
				comment = Comment (name = comment);
				comment.save ();
			else:
				comment = Comment.objects.get (id = 2);
			recommendation = request.POST.get ('recommendation', '');
			if recommendation:
				recommendation = Comment (name = recommendation);
				recommendation.save ();
			else:
				recommendation = Comment.objects.get (id = 2);
			if int (id) <= 0:
				data['name'] = Profile.objects.get (id = int(request.POST.get ('profile', id)));
			if leave_from and leave_to:
				visit = Visit (date = data['date'], profile = data['name'], comment = comment,
								recommendation = recommendation, leave_to = leave_to, leave_from = leave_from);
			else:
				visit = Visit (date = data['date'], profile = data['name'], comment = comment, recommendation = recommendation);
			visit.save ();
			return redirect ('/visit/%s' % visit.id);
	else:
		form = VisitForm ();
	return render_to_response ('visit/add.html', {'form':form, 'data':data},
								context_instance = RequestContext (request));

def autocomplete (request):
	complete = Profile.objects.filter (Q(first_name__istartswith=request.GET['term']) | Q(last_name__istartswith=request.GET['term']));
	results = [];
	for r in complete:
		results.append({'label':r.__unicode__ (), 'value':r.id})
	response = simplejson.dumps (results);
	return HttpResponse (response, content_type = 'application/json');

def error (request, title, message):
	return render_to_response ('info.html', {'title':title, 'msg':message},
								context_instance = RequestContext (request));

